/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[AutoLoginServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package cookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 利用Cookie实现自动登陆
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(name = "AutoLoginServlet", urlPatterns = "/autoLogin")
public class AutoLoginServlet extends HttpServlet {

	private static final long serialVersionUID = 2924995637309114675L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// username = Sean, password = 12345
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if ("Sean".equals(username) && "12345".equals(password)) {
			out.print("欢迎" + username);
			Cookie cookie1 = new Cookie("username", username);
			Cookie cookie2 = new Cookie("password", password);

			cookie1.setMaxAge(24 * 60 * 60);
			cookie2.setMaxAge(24 * 60 * 60);
			response.addCookie(cookie1);
			response.addCookie(cookie2);

			System.out.println("login with username/password");
		} else {
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				String cookieName = "";
				String cookiePass = "";
				for (int i = 0; i < cookies.length; i++) {
					if (cookies[i].getName().equals("username")) {
						cookieName = cookies[i].getValue();
					}
					if (cookies[i].getName().equals("password")) {
						cookiePass = cookies[i].getValue();
					}
				}
				if ("Sean".equals(cookieName) && "12345".equals(cookiePass)) {
					out.print("欢迎" + cookieName);
				} else {
					request.setAttribute("errorMsg", "用户名或密码不正确");
					request.getRequestDispatcher("/jsp/cookie/login.jsp").forward(request, response);
				}
			}
			System.out.println("login with cookie");
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
